package leetcode.code1658;

import leetcode.helper.MaxDebug;

public class Solution2 extends S1658 {

	@Override
	public int minOperations(int[] nums, int x) {
		int sum = 0;
		for (int num : nums) {
			sum += num;
		}
		int target = sum - x;
		if (target < 0) {
			return -1;
		}
		int Len = nums.length;
		int ans = Integer.MAX_VALUE;
		int L = 0;
		int R = 0;
		sum = 0;
		while (R < Len) { // 扩右去找
			if (sum == x) {
				ans = Math.min(ans, R - L);
				sum -= nums[L++];
			} else if (sum == target) {
				ans = Math.min(ans, Len - R + L);
				sum -= nums[L++];
			} else if (sum < target) {
				sum += nums[R++];
			} else {
				sum -= nums[L++];
			}
		}
		while (L < Len && (sum >= x || sum >= target)) {// 缩左去找
			if (sum == x) {
				ans = Math.min(ans, R - L);
			} else if (sum == target) {
				ans = Math.min(ans, Len - R + L);
			}
			sum -= nums[L++];
		}
		return ans == Integer.MAX_VALUE ? -1 : ans;
	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug6();
		so.debug5();
		so.debug4();
		MaxDebug.debug14(so);

	}

}
